package com.example.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author wen
 * @date 2021/8/19
 */
@Configuration
public class RedisConfig {

    /**
     * 注入 RedisTemplate
     * SpringBoot 自动在容器中生成了 RedisTemplate<Object,Object> 泛型不方便，重新注入一个<String,Object>
     *     可以直接在代码中
     *     @Resource
     *     private RedisTemplate<String,Object> redisTemplate;
     * @ConditionalOnMissingBean 如果容器中有 RedisTemplate，原本自动配置的 RedisTemplate 不会实例化
     * @return
     */
    @Bean
    //@ConditionalOnMissingBean("redisTemplate")
    public RedisTemplate<String,Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        //为string类型key设置序列器
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        //为string类型value设置序列器
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());

        //为hash类型key设置序列器
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        //为hash类型value设置序列器
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}
